<template>
    <div class="carLoan">
        <Form ref="carLoanForm" :model="carLoanForm" :rules="carLoanFormValiate" :label-width="90">
            <div class="common_content" style="padding: 0px;">
                 <Row>
                    <Col>
                        <FormItem label="车辆价格(元)" prop="carPrice">
                            <Input v-model="carLoanForm.carPrice"   placeholder="" :readonly="false" @on-change="inputPayPrice()"
                            :disabled="isShowDetails||pageIdentify=='assertChange'||isReconsider"  class="wprecent100"/>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                      <Col span="16">
                        <FormItem label="贷款期限(期)" prop="loanLimit" >
                            <InputNumber
                            :min="0"
                            class="wprecent100"
                             v-model="carLoanForm.loanLimit"
                             :disabled="isShowDetails||diffType=='details'"
                             @on-blur="inputLoanLimit"
                             @keyup.native="changeNumber"
                             ></InputNumber>
                        </FormItem>
                    </Col>
                    <Col span="8" style="text-align: right;">
                        <FormItem label="" :label-width="0" style="margin-left: 10px;">
                            <p style="display:inline-block" class="term">
                                默认区间:
                                <span v-for="(item,index) in term" :key="index" :class="{active:curSpan===index}" @click="selectTerm(item,index)"><i>{{item}}</i><b v-show="index!=term.length-1">~</b></span>
                            </p>
                        </FormItem>
                    </Col>
                </Row>
                 <Row style="display: flex;">
                      <Col span="12">
                        <FormItem label="首付比例(%)" prop="downPayScale" >
                            <Input v-model="carLoanForm.downPayScale"  placeholder="" @on-change="inputPayScale('downPayScale')" :disabled="isShowDetails||diffType=='details'"  class="wprecent100"/>
                        </FormItem>
                    </Col>
                    <Col span="12">
                        <FormItem label="首付金额(元)" prop="downPayAmt" style="margin-left: 10px;">
                            <Input v-model="carLoanForm.downPayAmt"  placeholder="" @on-change="inputPayAmt('downPayAmt')" :disabled="isShowDetails||diffType=='details'"  class="wprecent100"/>
                        </FormItem>
                    </Col>
                </Row>
                  <Row v-if="isCarTail" style="display: flex;">
                      <Col span="12">
                        <FormItem label="尾款比例(%)" prop="tailPayScale" >
                            <Input v-model="carLoanForm.tailPayScale"  placeholder="" @on-change="inputPayScale('tailPayScale')" :disabled="isShowDetails||diffType=='details'||isReconsider"  class="wprecent100"/>
                        </FormItem>
                    </Col>
                    <Col span="12">
                        <FormItem label="尾款金额(元)" prop="tailPayAmt" style="margin-left: 10px;">
                            <Input v-model="carLoanForm.tailPayAmt"  placeholder="" @on-change="inputPayAmt('tailPayAmt')" :disabled="isShowDetails||diffType=='details'||isReconsider"  class="wprecent100"/>
                        </FormItem>
                    </Col>
                </Row>
                 <Row>
                    <Col>
                        <FormItem label="贷款金额(元)" prop="loanAmt">
                            <Input v-model="carLoanForm.loanAmt"   placeholder="" @on-change="inputLoanAmt(carLoanForm.loanAmt)" :disabled="isShowDetails||diffType=='details'"  class="wprecent100"/>
                        </FormItem>
                    </Col>
                 </Row>
            </div>
        </Form>
    </div>
</template>
<script>
import * as utils from '_p/afs-apply/assets/js/utils.js'
import vueEvent from "_p/afs-apply/assets/js/vueEvent.js"
import {
    getProductRate,
} from "_p/afs-apply/api/apply-report/personal/financialProducts.js"
export default {
    name:"carLoan",
    data(){
        let validateTerm=(rule,value,callback)=>{
            if(value){
                if(value<this.term[0]||value>this.term[1]){
                    callback(new Error("请输入"+(this.term[0]||"")+"~"+(this.term[1]||"")+"期数"))
                    return;
               }
               if(this.valiateFlag){
                   if(value>this.queryCarProductInfo.costInfo.loanTerm){
                    callback(new Error("贷款期限不能变长"))
                    return;
                   }
               }
            }
            callback();
        }
        let valiateTailPayScale=(rule,value,callback)=>{
            if(value){
                if(value<=this.endBalancePaymentRange&&value>=this.fromBalancePaymentInterval){
                    if(this.carLoanForm.downPayScale){
                        if(utils.add(value,this.carLoanForm.downPayScale)>100){
                            callback(new Error("尾付与首付比例之和需小于等于100"))
                            return;
                        }
                    }
                }else{
                    callback(new Error('请输入'+this.fromBalancePaymentInterval+'~'+this.endBalancePaymentRange+'的尾款比例'))
                    return;
                }
            }
            callback();
        }
        let valiateTailPayAmt=(rule,value,callback)=>{
            if(value){
                if(value>this.endBalancePaymentRange||value<this.fromBalancePaymentInterval){
                    callback(new Error('请输入'+this.fromBalancePaymentInterval+'~'+this.endBalancePaymentRange+'的尾款金额'))
                    return;
                }
                if(value>this.carLoanForm.loanAmt){
                    callback('尾款金额应小于等于贷款金额');
                    return;
                }
            }
            callback();
        }
        let checkTailPayAmt=(rule,value,callback)=>{
            if(value){
                // console.log(value,this.carAdditioalLoanForm.loanAmt,"checkTailPayAmt")
                if(value>this.carLoanForm.loanAmt){
                    callback('尾款金额应小于等于贷款金额');
                    return;
                }
            }
            callback()
        }
        let valiateDownPayScale=(rule,value,callback)=>{
            if(value){
                if(value<=100&&value>=parseFloat(this.downPayRatioMin)){
                    if(this.carLoanForm.tailPayScale){
                        if(utils.add(value,this.carLoanForm.tailPayScale)>100){
                            callback(new Error("首付与尾付比例之和需小于等于100"))
                            return;
                        }
                    }
                }else{
                    callback(new Error('最低首付比例为'+this.downPayRatioMin+'%','最高首付比例为100%'))
                    return;
                }
            }
            callback();
        }
        let valiateLoanAmt=(rule,value,callback)=>{
            if(value){
                if(!utils.isTwoDicmal(value)) {
                    callback(new Error("最多为两位小数"))
                    return;
                }
                if(this.valiateFlag){
                    if(parseFloat(value)>parseFloat(this.queryCarProductInfo.costInfo.loanAmt)){
                        callback(new Error("贷额不能增加"))
                        return;
                    }
                }
                if(this.carLoanForm.tailPayAmt){
                    if(value<this.carLoanForm.tailPayAmt){
                        callback(new Error("贷款金额应大于等于尾款金额"))
                        return;
                    }
                }
            }
            callback();
        }
        let valitateDownPayScale=(rule,value,callback)=>{
            if(value){
                if(!utils.isTwoDicmal(value)) {
                    callback(new Error("最多为两位小数"))
                    return;
                }
                if(this.valiateFlag){
                    if(parseFloat(value)<parseFloat(this.queryCarProductInfo.costInfo.downPayScale)){
                        callback(new Error("首付比例不能降低"))
                        return;
                    }
                }
            }
            callback();
        }
        return{
            valiateTailPayScale:valiateTailPayScale,
            checkTailPayAmt:checkTailPayAmt,
            valiateTailPayAmt:valiateTailPayAmt,
            valiateDownPayScale:valiateDownPayScale,
            valitateDownPayScale:valitateDownPayScale,
            curSpan:"",
            finalPaymentBenchmark:"",
            term:[
                //    12,21
            ],
            tempCarRateList:[],
            carLoanForm:{
                carPrice: this.carPrice,
                loanLimit:0,
                downPayScale:"",
                downPayAmt:"",
                tailPayScale:"",
                tailPayAmt:"",
                loanAmt:"",
            },
            downPayRatioMin:"",
            fromBalancePaymentInterval:"",
            endBalancePaymentRange: "",
            carLoanFormValiate:{
                    carPrice:[
                        {required: true, message: "车辆价格不能为空", trigger: "blur"},
                        {validator:(rule,value,callback)=>{utils.isTwoDicmalValiate(rule,value,callback)},trigger:"blur"}
                    ],
                    loanLimit:[
                        {required: true, message:"贷款期限不能为空", trigger: "blur",type:"number"},
                        {validator:validateTerm,trigger: "blur",type:"number"}
                    ],
                    downPayScale:[
                        {required: true, message: "首付比例不能为空", trigger: "blur"},
                        {validator:valitateDownPayScale,trigger:"blur"}
                    ],
                    downPayAmt:[
                        {required: true, message: "首付金额不能为空", trigger: "blur"},
                        {validator:(rule,value,callback)=>{utils.isTwoDicmalValiate(rule,value,callback)},trigger:"blur"}
                    ],
                    tailPayScale:[
                        {required: true, message: "尾款比例不能为空", trigger: "blur"},
                        {validator:(rule,value,callback)=>{utils.isTwoDicmalValiate(rule,value,callback)},trigger:"blur"}
                    ],
                    tailPayAmt:[
                        {required: true, message: "尾款不能为空", trigger: "blur"},
                        {validator:(rule,value,callback)=>{utils.isTwoDicmalValiate(rule,value,callback)},trigger:"blur"}
                    ],
                    loanAmt:[
                        {required: true, message: "贷款金额不能为空", trigger: "blur"},
                        {validator:valiateLoanAmt,trigger:"blur"}
                    ]
            }
        }
    },
    computed:{
    },
    props:{
        queryCarProductInfo:{
            type:Object,
        },
        selectCarProductInfo:{
            type:Object,
        },
        isCarTail:{
            type:Boolean
        },
        uuid:{
            type:String,
        },
        carPrice:{
            type:String,
        },
        isShowDetails:{
            type:Boolean,
        },
        isReconsider:{
            type:Boolean,
        },
        diffType:{
            type:String,
        },
        mainProductId:{
            type:String
        },
        applyNo:{
            type:String
        },
        saveStatus:{
            type:Object
        },
        valiateFlag:{
            type:Boolean,
        },
        salePrice:{
            type:String,
        },
        isAutoCount:{
            type:Boolean
        },
        pageIdentify:{
            type:String
        }
    },
    watch:{
        carPrice(val){
            if(val){
                this.carLoanForm.carPrice=val;
                if(this.isAutoCount){
                    this.inputPayPrice()
                }
            }
        },
        salePrice(val){
            if(val){
                // this.carLoanForm.carPrice=val;
                this.$emit('changeCarPrice',val)

            }
        },
        selectCarProductInfo(val){
            if(Object.keys(val).length>0){
                let tempPeriod=[];
                tempPeriod[0]=val.detailInfo.loanPeriodMin;
                tempPeriod[1]=val.detailInfo.loanPeriodMax;
                this.term=tempPeriod;
                if(val.isTail=="1"){
                    this.fromBalancePaymentInterval=val.repaymentData.repaymentMethods.fromBalancePaymentInterval;
                    this.endBalancePaymentRange=val.repaymentData.repaymentMethods.endBalancePaymentRange;
                    this.finalPaymentBenchmark=val.repaymentData.repaymentMethods.finalPaymentBenchmark;
                    //  比例
                    if(val.repaymentData.repaymentMethods.intervalSelectionFinalPayment=='0'){
                        this.carLoanFormValiate['tailPayScale'].push({
                            validator: this.valiateTailPayScale,trigger:'blur'
                        })
                        this.carLoanFormValiate['tailPayAmt'].push({
                            validator: this.checkTailPayAmt,trigger:'blur'
                        })

                    }else if(val.repaymentData.repaymentMethods.intervalSelectionFinalPayment=='1'){
                        this.carLoanFormValiate['tailPayAmt'].push({
                            validator: this.valiateTailPayAmt,trigger:'blur'
                        })
                    }
                }
                this.downPayRatioMin=val.detailInfo.downPayRatioMin;
                this.carLoanFormValiate['downPayScale'].push({
                    validator: this.valiateDownPayScale,trigger:'blur'
                })
            }
        },
        queryCarProductInfo(val){
            console.log(val,"val-carLoan")
            if(Object.keys(val).length>0){
                //input的必输类型为string
                this.carLoanForm.carPrice=val.costInfo.contractAmt.toString();
                this.carLoanForm.loanLimit=val.costInfo.loanTerm;
                this.carLoanForm.downPayScale=val.costInfo.downPayScale.toString();
                this.carLoanForm.downPayAmt=val.costInfo.downPayAmt.toString();
                if(val.isTail=="1"){
                    this.carLoanForm.tailPayScale=val.costInfo.tailPayScale.toString();
                    this.carLoanForm.tailPayAmt=val.costInfo.tailPayAmt.toString();
                }
                this.carLoanForm.loanAmt=val.costInfo.loanAmt.toString();
            }
        },
        "carLoanForm.carPrice":{
            immediate: true,
            handler(val){
                vueEvent.$emit('to-carPrice',val,this.uuid);
            }
        },
        "carLoanForm.downPayAmt":{
            immediate: true,
            handler(val){
                vueEvent.$emit('to-carDownPayAmt',val,this.uuid);
            }
        },
        "carLoanForm.loanAmt":{
            immediate: true,
            handler(val){
                vueEvent.$emit('to-carLoanAmt',val,this.uuid);
            }
        }
    },
    created(){

    },
    mounted(){

    },
    beforeDestroy () {
    },
    methods:{
        changeNumber() {
            document.getElementsByClassName('ivu-input-number')[0].getElementsByTagName('input')[0].addEventListener('keyup', (e) => {
                let str = '' + e.target.value;
                if (str.indexOf('.') != -1) {
                    let arr = str.split('');
                    console.log(arr,"arr")
                    arr.splice(arr.length - 1);
                    let str2 = arr.join('');
                    e.target.value = +str2;
                }
            })
        },
        selectTerm(item,index){
            // 当为新增或编辑的时候
            if(!this.isShowDetails&&this.diffType!='details'){
                this.curSpan=index;
                this.carLoanForm.loanLimit=parseFloat(item);
                this.$refs.carLoanForm.validateField('loanLimit');
                this.matchRate(item);
            }
        },
        inputLoanLimit(){
            let loanLimit=parseFloat(this.carLoanForm.loanLimit);
            // 当验证通过才去调接口
            this.$refs.carLoanForm.validateField('loanLimit',(errorMsg)=>{
                if(!errorMsg){
                    this.matchRate(loanLimit)
                }
            });
        },
        // 匹配rate值
        matchRate(loanLimit){
            this.saveStatus.disabled=true;
            this.saveStatus.ismodify=true;
            let obj={
                applyNo:this.applyNo,
                id:this.mainProductId,
                loanTerm :loanLimit,
                costType:"01",
            }
            getProductRate(obj).then(res=>{
                if(res.code=="0000"){
                    if(res.data){
                        if(res.data.main){
                            let maxdiscountAmt="";
                            if(res.data.mainDiscount.discountOption!=0){
                                 maxdiscountAmt=res.data.mainDiscount.discountInfo.maxdiscountAmt;
                            }
                            vueEvent.$emit('to-carLoanRate',res.data.main.custRate,res.data.main.clearRate,res.data.main.addPointValue,maxdiscountAmt,this.uuid);
                        }else{
                            vueEvent.$emit('to-carLoanRate','','','','',this.uuid);
                        }
                    }
                }
            })

        },
        // 输入比例
        inputPayScale(type){
            this.saveStatus.disabled=true;
            this.saveStatus.ismodify=true;
            if(utils.isTwoDicmal(this.carLoanForm[type])){
                // 首付比例
                if(type=="downPayScale"){
                    this.$refs.carLoanForm.validateField('carPrice',(carPriceError)=>{
                        if(!carPriceError){
                            let multiplyAmt=utils.multiply(this.carLoanForm.carPrice,utils.divided(this.carLoanForm[type],100));
                            let payAmt=Math.round(multiplyAmt*100)/100;
                            this.carLoanForm.downPayAmt=payAmt.toString();
                            this.computedLoanAmt(this.carLoanForm.downPayAmt)
                        }
                    })
                }else if(type=="tailPayScale"){
                    let multiplyAmt="";
                    if(this.finalPaymentBenchmark=="0"||this.finalPaymentBenchmark=="2"){
                        this.$refs.carLoanForm.validateField('carPrice',(carPriceError)=>{
                            if(!carPriceError){
                                multiplyAmt=utils.multiply(this.carLoanForm.carPrice,utils.divided(this.carLoanForm[type],100));
                            }
                        })
                    }else if(this.finalPaymentBenchmark=="1"||this.finalPaymentBenchmark=="3"){
                        this.$refs.carLoanForm.validateField('loanAmt',(loanAmtError)=>{
                            if(!loanAmtError){
                                multiplyAmt=utils.multiply(this.carLoanForm.loanAmt,utils.divided(this.carLoanForm[type],100));
                            }
                        })
                    }
                    let payAmt=Math.round(multiplyAmt*100)/100;
                    this.carLoanForm.tailPayAmt=payAmt.toString();
                }
            }
            if(type=='downPayScale'){
                this.$refs.carLoanForm.validateField('downPayAmt');
                if(this.isCarTail){
                    if(this.carLoanForm.tailPayScale){
                        if(utils.add(this.carLoanForm.tailPayScale,this.carLoanForm.downPayScale)<=100){
                            this.$refs.carLoanForm.validateField('tailPayScale');
                        }
                    }
                }
            }else if(type=="tailPayScale"){
                this.$refs.carLoanForm.validateField('tailPayAmt');
                if(this.carLoanForm.downPayScale){
                    if(utils.add(this.carLoanForm.downPayScale,this.carLoanForm.tailPayScale)<=100){
                        this.$refs.carLoanForm.validateField('downPayScale');
                    }
                }
            }
        },
        // 输入金额
        inputPayAmt(type){
            this.saveStatus.disabled=true;
            this.saveStatus.ismodify=true;
            if(utils.isTwoDicmal(this.carLoanForm[type])){
                if(type=="downPayAmt"){
                    this.$refs.carLoanForm.validateField('carPrice',(carPriceError)=>{
                        if(!carPriceError){
                            let multiplyScale=utils.multiply(utils.divided(this.carLoanForm[type],this.carLoanForm.carPrice),100);
                            let payScale=Math.round(multiplyScale*100)/100;
                            this.carLoanForm.downPayScale=payScale.toString();
                            this.computedLoanAmt(this.carLoanForm[type]);
                        }
                    })
                }else if(type=="tailPayAmt"){
                    let multiplyScale="";
                    if(this.finalPaymentBenchmark=="0"||this.finalPaymentBenchmark=="2"){
                        this.$refs.carLoanForm.validateField('carPrice',(carPriceError)=>{
                            if(!carPriceError){
                                 multiplyScale=utils.multiply(utils.divided(this.carLoanForm[type],this.carLoanForm.carPrice),100);

                            }
                        })
                    }else if(this.finalPaymentBenchmark=="1"||this.finalPaymentBenchmark=="3"){
                        this.$refs.carLoanForm.validateField('loanAmt',(loanAmtError)=>{
                            if(!loanAmtError){
                                 multiplyScale=utils.multiply(utils.divided(this.carLoanForm[type],this.carLoanForm.loanAmt),100);
                            }
                        })
                    }
                    let payScale=Math.round(multiplyScale*100)/100;
                    this.carLoanForm.tailPayScale=payScale.toString();
                }
            }
            if(type=='downPayAmt'){
                this.$refs.carLoanForm.validateField('downPayScale');
            }else if(type=="tailPayAmt"){
                this.$refs.carLoanForm.validateField('tailPayScale');
            }
        },
        // 输入金额
        inputPayPrice(){
            if(utils.isTwoDicmal(this.carLoanForm.carPrice)){
                if(this.carLoanForm.downPayScale){
                    this.inputPayScale('downPayScale')
                }
                if(this.carLoanForm.tailPayScale){
                    this.inputPayScale('tailPayScale')
                }
            }
        },
        // 计算贷款金额
        computedLoanAmt(downPayAmt){
            let remainAmt=0;
            remainAmt=utils.sub(this.carLoanForm.carPrice,downPayAmt);
            this.carLoanForm.loanAmt=remainAmt.toString()||'';
            this.$refs.carLoanForm.validateField('loanAmt');
        },
        // 输入贷款金额
        inputLoanAmt(loanAmt){
            this.carLoanForm.downPayAmt=utils.sub(this.carLoanForm.carPrice,loanAmt).toString();
            this.inputPayAmt('downPayAmt');
        },
        submitCarLoan(){
            let carVailate=false;
            console.log(this.$refs.carLoanForm,this.$refs.carLoanForm.validate(),"this.$refs.carLoanForm.validate()")
            this.$refs.carLoanForm.validate((valid) => {
                if(valid){
                    carVailate=valid;
                }else{
                    carVailate=false;
                }
            })
            if(carVailate){
                return this.carLoanForm;
            }else{
                return false;
            }
        },
        // 清空数据
        resetCarLoan(){
            this.$refs["carLoanForm"].fields.forEach(function (e) {
                if (e.prop !="carPrice") {
                    e.resetField()
                }
            })
            // this.carLoanForm.carPrice=this.carPrice;
        }

    }
}
</script>
<style scoped>
.term span{
    height: 20px;
    display: inline-block;
    vertical-align: middle;
    line-height: 20px;
    margin-left: 5px;
    text-align: center;
    cursor: pointer;
}
.term span>i{
    font-style: normal;
    height: 20px;
    width: 20px;
    display: inline-block;
}
.term span.active>i,.term span>i:hover{
    background: #EB9620;
    color: white;
}
.w400{
    width: 400px;
}
</style>
